const app = getApp();
Page({
  data: {
    url: '', //登录界面地址 set
    weixinId: '',
    cookie: '',
  },
  
  //接收传参weixinId
  onLoad: function (options) {
    if (options.weixinId) {
      const weixinId = decodeURIComponent(options.weixinId);
      const url = `https://itlab.ctgu.edu.cn/labapi/login?next=https://itlab.ctgu.edu.cn/authBridge/setCookie/${encodeURIComponent(
        weixinId
      )}`;
      // 更新页面数据
      this.setData({
        weixinId: weixinId, //ZBtuzi
        url: url, //登录界面
      });
    } else {
      console.error('No weixinId received');
    }
  },
  //获取cookie
  onUnload: function () {
    //https://itlab.ctgu.edu.cn/labapi/login?next=https://itlab.ctgu.edu.cn/authBridge/setCookie/xiao2151636434
    const url = `https://itlab.ctgu.edu.cn/authBridge/getCookie/${encodeURIComponent(
      this.data.weixinId
    )}`;
    console.log('getcookie', url);
    const that = this;
    wx.request({
      url: url,
      success(res) {
        console.log(res);
        if (res.statusCode === 200) {
          console.log('Received data:', res.data);
          that.setData({
            cookie: res.data.cookie,
          });
          app.globalData.cookie=res.data.cookie
          app.saveGlobalData()
          //发送绑定微信请求
          wx.request({
            url: 'https://itlab.ctgu.edu.cn/labapi/BindWeiXin',
            method: 'POST',
            header: {
              Cookie: that.data.cookie,
            },
            data: { WeiXinID: that.data.weixinId },
            success: () => {
              console.log(res);
            },
          });
          app.globalData.alreadyLoggedIn = true;
          app.saveGlobalData();
          // 获取成功，跳转到指定界面
          console.log('获取成功，跳转到指定界面');
          wx.redirectTo({
            url: '/pages/index/index',
          });
        } else {
          // 获取失败，返回上一页
          wx.navigateBack({
            delta: 1,
          });
        }
      },
      fail(error) {
        console.log('请求失败，重新返回微信绑定界面');
        wx.redirectTo({
          url: 'pages/getweixinid/getweixinid',
        });
      },
    });
  },
});
